#!/usr/bin/envpython
#-*-coding:utf-8-*-
import re
from storagedata import models
from san.models import Wwn
import threading
import logging
logger = logging.getLogger('django')
def Re(res,total,id = "1"):
    if id == "1":
        data = re.findall(str(res),total)
    if id == "2":
        data = re.findall(str(res),total,re.S)
    return data
from storagedata.models import STLUN,STLUNgroup



#富士通添加存储id，返回 lun用啦多少，还有多少个lun可用，总共lun的大小
# def FST_lunnum(id):
#     group = STLUN.objects.filter(storage=id)
#     lunuse = 0
#     luntotal = 0
#     lunkeyong = 0
#     lunkeyongnum = 0
#     for i in group:
#         luntotal += float(i.lunsize)
#         if i.stlungroup_set.all():
#             lunuse += float(i.lunsize)
#         else:
#             lunkeyongnum += 1
#             lunkeyong += float(i.lunsize)
#
#
#     return [lunuse, luntotal,lunkeyong, lunkeyongnum]
#富士通存储,华为存储
def FST_lunnum(id):
    total = 0
    #总体的
    lungroup = STLUNgroup.objects.filter(storage=id)
    for i in lungroup:
        use = 0
        if i.stmap_set.all():
            for z in i.lun.all():
                use += float(z.lunsize)
        total += use
    group2 = Storage.objects.get(id = id)
    group2.ST_usecap = total
    group2.save()
    #map的数据
    lunmap = STMAP.objects.filter(storage = id)
    for i in lunmap:
        a = 0
        for z in i.manylungroup.all():
            for k  in z.lun.all():
                a += float( k.lunsize)
        i.totalcap = a
        i.save()
    return True

from storagedata.models import STMAP,Storage
#存储id#日立存储
def rili_lunnum(id):
    group = STMAP.objects.filter(storage=id)
    totaluse = 0
    for i in group:
        maplun = 0
        if i.manyhost.all():
            for k in i.manylun.all():
                maplun += float(k.lunsize)
            i.totalcap = round(maplun,1)
            totaluse += maplun
        i.save()
    if group:
        storage = Storage.objects.get(id = id)
        storage.ST_usecap =round(totaluse,1)
        storage.save()

#总的运行
from scriptd.tasks import Task

def sumcmount():
    task = Task()
    task.start("存储剩余容量计算")
    try:
        obj = Storage.objects.all()
        for i in obj:
            if i.ST_prodname == "富士通":
                FST_lunnum(i.id)
            elif i.ST_prodname == "日立":
                rili_lunnum(i.id)
            elif i.ST_prodname == "华为":
                FST_lunnum(i.id)
    except Exception as e:
        logger.error(e)
    task.end()